package com.guigu.handle;


import cn.hutool.core.map.MapUtil;
import cn.hutool.core.util.ObjectUtil;
import com.guigu.exception.GlobalException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.sql.SQLIntegrityConstraintViolationException;

/**
 * 全局异常控制器
 */
@RestControllerAdvice
@Slf4j
public class GlobalExceptionHandler {


    /**
     * 自定义异常处理
     *
     * @param exception 自定义异常
     * @return 响应数据
     */
    @ExceptionHandler(GlobalException.class)
    public ResponseEntity<Object> handle(GlobalException exception) {
        if (ObjectUtil.isNotEmpty(exception.getCause())) {
            log.error("自定义异常处理 -> ", exception);
        }
        return ResponseEntity.status(exception.getStatus())
                .body(MapUtil.<String, Object>builder()
                        .put("code", exception.getCode())
                        .put("msg", exception.getMsg())
                        .put("status",exception.getStatus())
                        .build());
    }


    /**
     * 处理SQL异常
     * @param exception
     * @return
     */
    @ExceptionHandler
    public ResponseEntity<Object> sqlExceptionHandler(SQLIntegrityConstraintViolationException exception){
        //Duplicate entry 'zhangsan' for key 'employee.idx_username'
        String message = exception.getMessage();
        String msg = "";
        if(message.contains("Duplicate entry")){
            //用户名已经存在
            //根据空格来分割字符串得到数组对象
            String[] split = message.split(" ");
            String username = split[2];
             msg = username + "已存在";
        }else {
            msg = "未知错误";
        }
        return ResponseEntity.status(500)
                .body(MapUtil.<String, Object>builder()
                        .put("code",1001)
                        .put("msg", msg)
                        .build());
    }
}
